<?php
namespace app\components;
use Yii;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoom;

use app\modules\Product\models\Product;
use app\modules\Product\models\ProductRoom;
use app\modules\Product\models\ProductRoomPrice;
use app\modules\Product\models\ProductFlight;

use app\modules\Finance\models\Finance;
use app\modules\Finance\models\FinanceOrder;

use yii\console\Exception;

/**
 * 订单处理类
 */
class OrderBlock extends \yii\base\Widget
{
    //public $auth      = "";


    /**
     * Starts recording a block.
     */
    public function init()
    {
		/******* init *********/
    }


	/**
	 * @param $data    ARRAY
	 * @param $order   OBJECT   order 
	 *
	 */
	public function create($data, $order, $insert=1){//{{{
        $all = isset($data['room']) ? $data['room'] : NULL;
        if($all){
            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();
			//print_r($all);exit;
            try{
				$price = 0;
                foreach($all as $room){
					//  获取当前已售出库存数  // 判断库存是否足够
                    $productroom = ProductRoom::findOne($room['id']);

					$sell_num = OrderRoom::find()->where(['product_id'=>$order->product_id, 'room_id'=>$productroom->id, 'status'=>1, 'stock'=>1])->count();

                    // 新增订单 减少库存数
                    $model = new OrderRoom();
                    $model->product_id = $order->product_id;
                    $model->order_id = $order->id;
                    $model->room_id  = $room['id']; // table: product_room_price 
                    $model->num      = $room['num'];

                    $num = $productroom->num - 1 - $sell_num;

                    if($num < 0 ){
                		$transaction->rollBack();
						// 新增情况 删除订单基础部分
						if($insert == 1){
							$order->delete();
						}
						echo "订单舱房保存失败, 库存数不足";
						exit;
                    }

					//设置价格 
					if($order->source == 1){  //直客价格
						$price += ($productroom->price * $model->num); // product room price table
						$model->price = ($productroom->price * $model->num);
					}elseif($order->source == 2){ // 同业价格
						$price += ($productroom->inside_price * $model->num); // product room price table
						$model->price = ($productroom->inside_price * $model->num);
					}

                    if(! $model->save()){
                		$transaction->rollBack();
						echo "订单舱房保存失败, 请重新添加.";
						exit;
						//return false;
                        throw new Exception('订单舱房保存失败, 请重新添加.');
                    }
                }
				$order->total_sale = $order->total_sale + $price;
				$order->price = $order->price + $price;
				$order->save();

                $transaction->commit();
            }catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }
	}//}}}


	public function create2($data, $order , $insert=1){//{{{
        $all = isset($data['room']) ? $data['room'] : NULL;

        if($all){
            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();

            try{
				$price = 0;
                foreach($all as $room){
					$sell_num = OrderRoom::find()->where(['product_id'=>$order->product_id, 'room_id'=>$room['id'], 'status'=>1, 'stock'=>1])->count();
                    // 新增订单 减少库存数
                    $model = new OrderRoom();
                    $model->product_id = $order->product_id;
                    $model->order_id = $order->id;
                    $model->room_id  = $room['id']; // table: product_room_price 
                    $model->num      = $room['num'];


                    // 减少库存
					//$product = Product::findOne($data['Order']['product_id']);
					$product = Product::findOne($order->product_id);
					$rooms = json_decode($product->rooms, true);
					$room_item   = $rooms[$room['id']];

                    $num = $room_item['num'] - $sell_num - 1;

                    if($num < 0 ){
                		$transaction->rollBack();
						// 新增情况 删除订单基础部分
						if($insert == 1){
							$order->delete();
						}
						echo "订单舱房保存失败, 库存数不足.";
                        //throw new Exception('订单舱房保存失败, 库存数不足.');
						exit;
                    }

					//设置价格 
					if($order->source == 1){  //直客价格

						if($model->num <= 2){// 判断人数是否含有三四人价格
							$p = ($rooms[$room['id']]['price'] * $model->num);

							$price += $p; // product room price table
							$model->price = $p;

						}elseif($model->num > 2){
							$price1 = empty($rooms[$room['id']]['price']) ? 0 : $rooms[$room['id']]['price'];
							$price2 = empty($rooms[$room['id']]['price2']) ? $price1 : $rooms[$room['id']]['price2'];

							$p = ($price1 * 2) + ($price2 * ($model->num -2));
							$price += $p; // product room price table
							$model->price = $p;
						}

					}elseif($order->source == 2){ // 同业价格
						//$price += ($rooms[$room['id']]['inside_price'] * $model->num); // product room price table
						//$model->price = ($rooms[$room['id']]['inside_price'] * $model->num);
						if($model->num <= 2){// 判断人数是否含有三四人价格
							$p = ($rooms[$room['id']]['inside_price'] * $model->num);

							$price += $p; // product room price table
							$model->price = $p;

						}elseif($model->num > 2){
							$price1=empty($rooms[$room['id']]['inside_price']) ? 0 : $rooms[$room['id']]['inside_price'];
							$price2=empty($rooms[$room['id']]['inside_price2']) ? $price1 : $rooms[$room['id']]['inside_price2'];

							$p = ($price1 * 2) + ($price2 * ($model->num -2));
							$price += $p; // product room price table
							$model->price = $p;
						}
					}

                    if(! $model->save()){
                		$transaction->rollBack();
						echo "订单舱房保存失败, 请重新添加.";
                        //throw new Exception('订单舱房保存失败, 请重新添加.');
						exit;
                    }
                }
				$order->total_sale = $order->total_sale + $price;
				$order->price = $order->price + $price;
				$order->save();

                $transaction->commit();
            }catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }

	
	}//}}}
	
	/* 
	 * 判断订单库存是否充足
	 * @param 	order 		MODEL
	 * @param 	room_id 	INT
	 *
	 */
	public function isStock($order){//{{{
		// 获取订单中每种舱房的使用数量
		$data = OrderRoom::find()->where(['order_id'=>$order->id])->all();

		if($data){
			$stock = [];
			foreach($data as $room){
				$stock[$room->room_id][] = $room->id;   // room_id  is product_room_price id
			}
			//print_r($stock);exit;
			$ret = true;
			foreach($stock as $key=>$val){  // 房间编号=> order_room->id  多维数组 每个代表一间房
				if($order->product->stock == 1){ // 标准库存格式

					$product_room = ProductRoom::findOne($key);

					$total = $product_room->num; // 库存总数

					//  获取房型售出数量
					$sell_num = OrderRoom::find()->where(['product_id'=>$order->product_id,'room_id'=>$key,'status'=>1, 'stock'=>1])->count();
				}else{ // 海外 船票
				
					$rooms = json_decode($order->product->rooms, true);
					if($rooms){

						$room_item = $rooms[$key];
                    	$total = $room_item['num'];

						$sell_num = OrderRoom::find()->where(['product_id'=>$order->product_id, 'room_id'=>$key, 'status'=>1])->count();
					}else{
						$sell_num = 0;
						$total = 0;
					}
				}
				 
				if( ($sell_num+count($val)) <= $total){
					$ret = true;
				}else{
					return false;
				}
			}

			return $ret;
		}else{
			// 该订单没有选择舱房
			return true;
		}
	}//}}}

	/**
	 *	财务审批对应 订单状态变更流程
	 *	@param  finance	OBJECT
	 *  @param  type 	INT    (1 收款  2 应收账款 3 退款)
	 * 
	 */
	public function status($finance){//{{{

		$data = $finance->order;

		if($finance->type == 1){ //收款
			
			foreach($data as $finance_order){
				$price = $finance_order->price; // 本次收款金额

				// 获取订单以往累积收款金额
				$query = FinanceOrder::find();
				$query->joinWith(['finance']);

				$query->where(['finance_order.order_id' => $finance_order->order_id]);
				$query->andWhere(['finance.status' => 3])->andWhere(['!=', 'finance_order.id', $finance_order->id]);
				$p = $query->sum("finance_order.price");


				// 获取订单以往退款金额 
				$query2 = FinanceOrder::find();
				$query2->joinWith(['finance']);

				$query2->where(['finance_order.order_id' => $finance_order->order_id]);
				$query2->andWhere(['finance.status' => 3, 'type'=>3])->andWhere(['!=', 'finance_order.id', $finance_order->id]);
				$p2 = $query2->sum("finance_order.price");


				// 该订单已通过审批的金额
				$total_price = empty($p) ? 0 : (int)$p;
				$p2 = empty($p2) ? 0 : (int)$p2;
				$total_price = $total_price - $p2; 
				//$total_price = empty($p) ? 0 : (int)$p;  	//	var_dump($total_price);

				// 收款总金额大于等于 订单实际金额  状态变更为已付款
				$order = Order::findOne($finance_order->order_id);

				if( ($total_price+$price) >= $order->price){
					
					$order->status = 3;
				}elseif(($total_price+$price) > 0 ){

					$order->status = 2;
				}elseif(($total_price+$price) == 0 ){
					
					$order->status = 2;
				}
				
				$order->save();
			}

		}elseif($finance->type == 3){  // 退款
				
			foreach($data as $finance_order){
				$price = $finance_order->price; // 本次退款金额

				// 获取订单以往累积收款金额
				$query = FinanceOrder::find();
				$query->joinWith(['finance']);

				$query->where(['finance_order.order_id' => $finance_order->order_id]);
				$query->andWhere(['finance.status' => 3, 'type'=>1])->andWhere(['!=', 'finance_order.id', $finance_order->id]);
				$p = $query->sum("finance_order.price");

				// 获取订单以往退款金额 
				$query2 = FinanceOrder::find();
				$query2->joinWith(['finance']);

				$query2->where(['finance_order.order_id' => $finance_order->order_id]);
				$query2->andWhere(['finance.status' => 3, 'type'=>3])->andWhere(['!=', 'finance_order.id', $finance_order->id]);
				$p2 = $query2->sum("finance_order.price");



				// 该订单已通过审批的金额
				$total_price = empty($p) ? 0 : (int)$p;
				$p2 = empty($p2) ? 0 : (int)$p2;
				$total_price = $total_price - $p2; 

				// 收款总金额大于等于 订单实际金额  状态变更为已付款
				$order = Order::findOne($finance_order->order_id);
				
				if( ($total_price-$price) >= $order->price){
					
					$order->status = 3;
				}elseif( (($total_price-$price)>0 )  && (($total_price-$price) < $order->price) ){

					$order->status = 2;
				}elseif(($total_price-$price) <= 0){
				
					$order->status = 1;
				}
				$order->save();
			}
		}
	}//}}}

	/**
	 *	根据订单金额相应变更订单当前状态
	 *	@param	order	OBJECT
	 *
	 */
	public function order_status($order){//{{{
		// 获取订单实收金额
		$finance_price = $order->financeSuccess;

		if($order->price <= $finance_price ){ // 付全款

			$order->status = 3;
		}elseif( ($order->price > $finance_price) && ($finance_price > 0) ){  // 定金
		
			$order->status = 2;
		}elseif($finance_price == 0){ // 未付款  占位
			
			$order->status = 1;
		}

		$order->save();
	}//}}}

	/**
	 *	判断订单佣金金额是否超出限制
	 *	@param	price 	FLOAT	佣金金额
	 *	@return BLOOEN
	public function commiss($order){//{{{
		$rooms = $order->room; 	// 获取订单对应的舱房

		$max_price = 0;

		if($rooms){
			foreach($rooms as $room){
				$product_room = $room->productRoom;		//
				$max_price += $product_room->commiss_price;
			}
		}
		
		$ret = true;

		if($order->commiss_price > $max_price){
			// 佣金超过最大限制	将佣金重置为0
			$order->commiss_price = 0;
			$ret = $max_price;
		}

		// 计算优惠金额	及 佣金金额  todo
        $price = $order->total_sale - $order->sale_price - $order->commiss_price;

		// 计算附加费金额
		if($order->priceSum){
			$price = $price+$order->priceSum;
		}

        $price = ($price <=0) ? 0 : $price;
        $order->price = $price;

		$order->save();

		return $ret;
	}//}}}
	 */
	public function commiss($orderRoom){//{{{
		$ret = true;

		$max_price = $orderRoom->maxCommiss; // 佣金上线

		if($orderRoom->commiss_price > $max_price){
			// 佣金超过最大限制	将佣金重置为 0	// $ret = $max_price;
			$orderRoom->commiss_price = $max_price;
			$ret = $max_price;
		}

		$orderRoom->save();

		$order = $orderRoom->order;

		// 计算优惠金额	及 佣金金额  todo
        $price = $order->total_sale - $order->sale_price - $order->commiss;

		// 计算附加费金额
		if($order->priceSum){
			$price = $price+$order->priceSum;
		}

        $price = ($price <=0) ? 0 : $price;
        $order->price = $price;

		$order->save(); // 更新订单金额

		return $ret;
	}//}}}

}
